﻿using System;
using System.Data;
using S3.DataModel;

namespace S3.Biz
{
    public class CommonManager : System.IDisposable
    {
        internal S3Entities _entities;
        internal bool _transactionFlag;

        public CommonManager()
        {
            if (_entities == null)
            {
                _entities = new S3Entities();

            }
        }

        public S3Entities DataContext
        {
            get
            {
                if (_entities == null)
                {
                    _entities = new S3Entities();
                }
                return _entities;
            }
        }

        public IDbTransaction BeginTransaction()
        {
            // Set flag
            _transactionFlag = true;
            // Start _trans
            _entities.Connection.Open();
            return _entities.Connection.BeginTransaction();
        }

        public void CommitTransaction(IDbTransaction transaction)
        {
            // Set flag
            _transactionFlag = false;
            // Start _trans                        
            if (transaction != null && _entities.Connection.State != ConnectionState.Closed)
            {

                transaction.Commit();
                transaction.Dispose();
            }
        }

        public void RollbackTransaction(IDbTransaction transaction)
        {
            // Set flag
            _transactionFlag = false;
            // Start _trans
            if (transaction != null && _entities.Connection.State != ConnectionState.Closed)
            {
                transaction.Rollback();
                transaction.Dispose();
                transaction = null;
            }
        }

        protected virtual void Dispose(bool isDispose)
        {
            if (isDispose)
            {
                _entities.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }
}

